package com.crimsec.utils.snmp.service;

import com.crimsec.utils.snmp.model.Event;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

@Stateless
public class EventService {

    @PersistenceContext(unitName = "jsnmp")
    EntityManager em;

    public long getCount() {
        TypedQuery<Long> qc = em.createQuery("SELECT Count(e) FROM Event e", Long.class);
        //TODO: check null here
        return qc.getSingleResult().longValue();
    }

    /**
     *
     * @param id
     * @return an Event
     */
    public Event get(long id) {
        return em.find(Event.class, id);
    }

    /**
     * @return список snmp событий
     *
     * The transactional attribute ‘Supports’ defines that the transactional
     * mode has to be propagated from the caller to the business method that is
     * annotated with ‘Supports’. This means that if the caller is in an active
     * transaction, then the business method will also execute as part of the
     * active transaction. This means that a failure in the business method will
     * revert the caller’s transaction also. If the caller is not part of the
     * transactional context, then the business method will also execute in a
     * non-transactional context.
     *
     */
    @TransactionAttribute(TransactionAttributeType.SUPPORTS)
    public List<Event> getEventList(/* TODO: использовать Criteria API
             для возврата списка частями*/) {
        TypedQuery<Event> qEvents = em.createNamedQuery("Event.findAll", Event.class);
        return qEvents.getResultList();

    }

    public Event insert(Event e) {
        em.persist(e);
        return e;
    }

    public Event update(Event e) {
        em.merge(e);
        return e;
    }

    public void delete(long eventId) {
        em.remove(get(eventId));
    }
}
